package com.xcm.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by YPZS on 17/11/27.
 */
public class FileUtils {

    /**
     * 读取文件
     *
     * @param path
     * @return
     */
    public static String readFile(String path) {
        StringBuffer laststr = new StringBuffer("");
        File file = new File(path);// 打开文件
        BufferedReader reader = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));// 读取文件
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr.append(tempString);
            }
            reader.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException el) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException el) {
                }
            }
        }
        return laststr.toString();
    }

    /**
     * 保存文件
     *
     * @param url
     * @param name
     * @param retry
     */
    public static void saveUrlAs(String url, String name, int retry) throws UnsupportedEncodingException {
        //System.out.println("fileName---->"+filePath);
        //创建不同的文件夹目录
        if (retry <= 0) {
            return;
        }

        //json文件存放目录
        String jsonFilePath = PropertyFileUtils.getPropertyValueByKey("application-dev", "xcips.json.file.save.path");
        File file = new File(jsonFilePath);
        //判断文件夹是否存在
        if (!file.exists()) {
            //如果文件夹不存在，则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            // 建立链接
            URL httpUrl = new URL(url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream = conn.getInputStream();
            bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            if (!jsonFilePath.endsWith("/")) {

                jsonFilePath += "/";

            }
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileOut = new FileOutputStream(jsonFilePath + name);
            bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[1024];
            int length = bis.read(buf);
            //保存文件
            while (length != -1) {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
        } catch (Exception e) {
            e.printStackTrace();
            saveUrlAs(url, name, retry-1);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (fileOut != null) {
                    fileOut.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        //return file;
    }
}
